﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTests
{
	/// <summary>
	/// Utilities for unit testing.
	/// </summary>
	public class Utils
	{
		private static string Serialize<T>(T theObject) where T : class
		{
			var buffer = new StringBuilder();
			using (var writer = XmlWriter.Create(buffer))
			{
				var serializer = new XmlSerializer(typeof(T));
				serializer.Serialize(writer, theObject);
				return buffer.ToString();
			}
		}

		private static T Deserialize<T>(string xmlText) where T : class
		{
			using (var reader = new StringReader(xmlText))
			{
				var serializer = new XmlSerializer(typeof(T));
				return (T)serializer.Deserialize(reader);
			}
		}

		/// <summary>
		/// Checks, if a deserialized object is equal to original object. 
		/// </summary>
		/// <typeparam name="T">Specifies the class of the object to serialize/deserialize.</typeparam>
		/// <param name="originalObject">Specifies the original object.</param>
		public static void TestXmlSerialization<T>(T originalObject) where T : class
		{
			var serializedText = Serialize(originalObject);
			var deserializedObject = Deserialize<T>(serializedText);

			var originalObjectText = originalObject.ToString();
			var deserializedObjectText = deserializedObject.ToString();
			Assert.AreEqual(originalObjectText, deserializedObjectText);
		}
	}
}
